package com.sjl.record;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * MediaRecorderUtil
 *
 * @author SJL
 * @date 2021/7/15
 */
public class MediaRecorderUtil {

    //设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025, 8000
    private final int sampleRateInHz = 8000;
    //设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
    private final int channelConfig = AudioFormat.CHANNEL_IN_MONO;
    //音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
    private final int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    //录制状态
    private boolean recorderState = true;
    private byte[] buffer;
    private MediaRecorder mediaRecorder;
    private static MediaRecorderUtil mediaRecorderUtil = new MediaRecorderUtil();

    public static MediaRecorderUtil getInstance() {
        return mediaRecorderUtil;
    }

    private MediaRecorderUtil() {
        init();
    }

    private void init() {
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSamplingRate(8000);
        mediaRecorder.setAudioChannels(1);
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);//音频录入源
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);//录制音频的输出格式
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//录制音频的编码格式  目前手机设备上可能就AMR_NB有用
        mediaRecorder.setOutputFile(Environment.getExternalStorageDirectory().getPath() + "/mediaAAC.aac");//音频输出路径和文件名称　注意!这个设置是有顺序要求的,必需是上面编码格式设置完成后才能,写到前面会报错
        mediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
            @Override
            public void onError(MediaRecorder mr, int what, int extra) {
                //异常监听
                mediaRecorder.stop();//暂停
                mediaRecorder.release();//释放资源
                mediaRecorder = null;
            }
        });
        mediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {//信息回调
            @Override
            public void onInfo(MediaRecorder mr, int what, int extra) {

            }
        });
    }

    /**
     * 开始录制
     */
    public void start() {
        if (mediaRecorder != null){
            try {
                mediaRecorder.prepare();//准备
                mediaRecorder.start();//开启
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 停止录制
     */
    public void stop() {
        if (mediaRecorder != null){
            mediaRecorder.stop();//暂停
            mediaRecorder.release();
        }
    }

}
